<?php

namespace App\Console\Commands;

use App\Library\Logger;
use App\Models\CityModel;
use App\Models\Customer;
use App\Models\DeptModel;
use App\Models\Product;
use Carbon\Carbon;
use Illuminate\Console\Command;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class ImportProduct extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'import:product';

    private $logger;

    private $truncateTable = true;

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '批量导入商品数据';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->logger = new Logger('commands/import_product');
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $bench = new \Ubench();
        $bench->start();

        $this->truncateTable();
        $this->handleProducts();

        $bench->end();
        $this->logger->debug("time used: " . $bench->getTime());
        $this->logger->debug("memory used: " . $bench->getMemoryUsage());
    }

    private function handleProducts()
    {
        $this->logger->info("handle excel file start...");
        $file = public_path('resources/products/') . 'import-product.xlsx';
        if (!is_file($file)) {
            $this->logger->error("file is not exist!");
            return;
        }

        $reader = IOFactory::createReader('Xlsx');
        $reader->setReadDataOnly(true);
        $spreadsheet = $reader->load($file);
        $worksheets = $spreadsheet->getAllSheets();

        foreach ($worksheets as $index => $worksheet) {
            $tempIndex = $index + 1;
            $this->logger->info("处理第{$tempIndex}个表格");
            $this->handleItemSheet($worksheet);
        }
    }

    private function handleItemSheet(Worksheet $sheet)
    {
        $rowCount = $sheet->getHighestRow();
        if ($rowCount < 2) {
            $this->logger->info("no record in this sheet");
            return;
        }
        for ($i = 2; $i <= $rowCount; $i++) {
            $customerName = trim($sheet->getCellByColumnAndRow(2, $i)->getValue() ?? '');
            $customer = Customer::byName($customerName)->first();
            if (empty($customer)) {
                $this->logger->info("customer is empty, name: {$customerName}");
                continue;
            }
            $departmentName = trim($sheet->getCellByColumnAndRow(7, $i)->getValue() ?? '');
            $departmentName = str_replace('区', '', $departmentName);
            $department = DeptModel::byName($departmentName)->first();
            if (empty($department)) {
                $this->logger->info("department is empty, name: {$departmentName}");
            }

            $customerId = $customer->id;
            $productName = trim($sheet->getCellByColumnAndRow(3, $i)->getValue() ?? '');
            $productModel =  trim($sheet->getCellByColumnAndRow(4, $i)->getValue() ?? '');
            $productNumber = trim($sheet->getCellByColumnAndRow(5, $i)->getValue() ?? '');
            $productDateBuy = trim($sheet->getCellByColumnAndRow(6, $i)->getValue() ?? '');
            try {
                $productDateBuy = Carbon::parse($productDateBuy)->toDateString();
            } catch (\Exception $e) {
                $this->logger->info("购买日期错误: {$productName} - {$productDateBuy}");
            }
            $productDepartmentId = $department->id ?? 0;

            $provinceName = trim($sheet->getCellByColumnAndRow(8, $i)->getValue() ?? '');
            $province =CityModel::byName($provinceName)->first();
            $productProvinceId = $province->id ?? 0;
            $productProvinceName = $province->name ?? '';

            $cityName = trim($sheet->getCellByColumnAndRow(9, $i)->getValue() ?? '');
            $city =CityModel::byName($cityName)->first();
            $productCityId = $city->id ?? 0;
            $productCityName = $city->name ?? '';

            $countyName = trim($sheet->getCellByColumnAndRow(10, $i)->getValue() ?? '');
            $county =CityModel::byName($countyName)->first();
            $productCountyId = $county->id ?? 0;
            $productCountyName = $county->name ?? '';

            $productInstallAddress = trim($sheet->getCellByColumnAndRow(11, $i)->getValue() ?? '');
            $productWarrantyStart = trim($sheet->getCellByColumnAndRow(12, $i)->getValue() ?? '');
            try {
                $productWarrantyStart = Carbon::parse($productWarrantyStart)->toDateString();
            } catch (\Exception $e) {
                $this->logger->info("质保开始时间错误: {$productName} - {$productWarrantyStart}");
            }
            $productWarrantyEnd = trim($sheet->getCellByColumnAndRow(13, $i)->getValue() ?? '');
            try {
                $productWarrantyEnd = Carbon::parse($productWarrantyEnd)->toDateString();
            } catch (\Exception $e) {
                $this->logger->info("质保结束时间错误: {$productName} - {$productWarrantyEnd}");
            }

            $productData = [
                'customer_id' => $customerId,
                'department_id' => $productDepartmentId,
                'product_number' => $productNumber,
                'name' => $productName,
                'model' => $productModel,
                'province_id' => $productProvinceId,
                'province_name' => $productProvinceName,
                'city_id' => $productCityId,
                'city_name' => $productCityName,
                'county_id' => $productCountyId,
                'county_name' => $productCountyName,
                'install_address' => $productInstallAddress,
                'date_buy' => $productDateBuy,
                'warranty_start' => $productWarrantyStart,
                'warranty_end' => $productWarrantyEnd
            ];
            $this->logger->info("导入数据");
            $this->logger->info($productData);
            $product = new Product();
            $product->fill($productData);
            $product->saveOrFail();
        }
    }

    // 清空原始商品数据
    private function truncateTable()
    {
        if (!$this->truncateTable) {
            return;
        }
        Product::query()->truncate();
    }
}
